/*
 * ringtonevolumehelper.m
 * 
 * Copyright (c) 2009 nathulal <inathulal at gmail.com>. All rights reserved.
 * Credits also due to rbisconti97 (xsellize dot com) for his research on the
 * Celestical.framework plist files
 * 
 * This file is part of SBSilentToggle.
 * 
 * SBSilentToggle is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * SBSilentToggle is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with SBSilentToggle.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <notify.h>
#include <notify.h>
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>


int main(int argc, char **argv) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
	[numFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
	NSNumber *ringtoneValue = [numFormatter numberFromString:@"0.5"];

	if(argc != 2 && argc != 3)
		goto noaction;
	
	if(argc == 3)
	{
		NSString *ringtoneStringValue = [NSString stringWithUTF8String: argv[2]];
		ringtoneValue = [numFormatter numberFromString:ringtoneStringValue];
	}
	
	NSString *prefsFile = [NSString stringWithUTF8String: argv[1]];
	NSMutableDictionary *prefs = [[NSMutableDictionary alloc] initWithContentsOfFile:prefsFile];
	
	if (prefs != nil) {
        [prefs autorelease];
		
		id volumes = [prefs objectForKey:@"volumes"];
		if(volumes != nil)
		{
			id broadcast = [volumes objectForKey:@"broadcast"];
			if(broadcast != nil)
			{
				if(argc == 2)
				{
					if([broadcast containsKey:@"Ringtone"])
					{
						ringtoneValue = [broadcast valueForKey:@"Ringtone"];
					}
				}
				else
				{
					[broadcast setObject:ringtoneValue forKey:@"Ringtone"];
					[prefs writeToFile:prefsFile atomically:YES];
				}
			}
		}
	}
	fprintf(stdout, "%s\n", [[ringtoneValue stringValue] cString]);
noaction:
	[numFormatter release];
	[pool release];
	return 0;
}
